﻿--[[
   @brief    descprtion
   @author   rickonzhang
   @version  1.0
   @date     2015-06-10
--]]
friend_tips_control = 
{
    cache_time = 300; --5分钟
    data_cache = {};
    game_cache = {};
    friend_recent_game_list = {};

    init = function()
        base_utility.log("[friend_tips_control] init")
        comm_center.listen_broadcast('i_service_call_tgp_get_recent_game_list', friend_tips_control.service_call_tgp_get_recent_game_list);
        comm_center.listen_broadcast("i_broadcast_open_msg_setting", friend_tips_control.open_msg_setting);

        comm_center.reg_service("i_service_show_wegame_online_tips", friend_tips_control.handle_show_wegame_online_tips);
        comm_center.reg_service("i_service_show_game_online_tips", friend_tips_control.handle_show_game_online_tips);
        comm_center.listen_broadcast("i_service_game_online_tips_dl_game", friend_tips_control.handle_game_online_tips_dl_game);
        comm_center.listen_broadcast("i_service_game_online_tips_start_game", friend_tips_control.handle_game_onlie_tips_start_game);
    end;

    get_valid_data = function(friend_id)
        local friend_data_cache = nil;
        if friend_tips_control.data_cache[friend_tips_view.friend_id] ~= nil then
            local old_time = friend_tips_control.data_cache[friend_tips_view.friend_id]["time"];
            local new_time = os.time();
            if new_time - old_time < friend_tips_control.cache_time then --缓存时间小于5分钟
                base_utility.log("[friend_tips_control]缓存时间<5分钟");
                friend_data_cache = friend_tips_control.data_cache[friend_tips_view.friend_id]["cache"];
            else
                friend_tips_control.data_cache[friend_tips_view.friend_id] = nil;
                base_utility.log("[friend_tips_control]缓存时间>=5分钟,下次显示要更新:tgp_id:"..friend_id);
            end
        end
        return friend_data_cache;
    end;


    show = function(event_id, json_str)
        ierd_tgp.tpf_ui.Require("social\\friend_tips\\view.lua")
        local param = base_utility.json_to_table(json_str)
        if param["bShow"] == true then
            if param["friend_id"] == login_model.im_login_infomation.friend_id then
                tqos_mgr.increase_self_card_show_success_count();
            else
                tqos_mgr.increase_friend_card_show_success_count();
            end

            local is_first_create = false;
            if friend_tips_view.pDialog == nil then
                is_first_create = true;
            end;

            friend_tips_view.show(true, param["friend_id"]);
            friend_tips_view.move(param["x"] - 20, param["y"] - 7);
            if is_first_create ~= true then --非第一次加载html
                friend_tips_control.user_info();
            end

            friend_tips_view.reset_size(true);
            -- local f_game_list = friend_tips_control.query_friend_recent_game_list(friend_tips_view.friend_id);
            -- if f_game_list ~= nil then
            --     friend_tips_view.reset_size(true);
            -- else                    
            --     friend_tips_view.reset_size(false);
            -- end

            local id_list = {};
            table.insert(id_list, param["friend_id"]);
            friend_tips_control.get_recent_play_game_list(id_list);
        else
            friend_tips_view.show(false, nil, param["action"]);
        end
    end;

    on_navigate_complete = function()
        base_utility.log("[friend_tips_control]on_navigate_complete");
    end;

    on_js_callback = function(uilib, func_name, json_str, ctrl_id)
        base_utility.log("[friend_tips_control] on_js_callback, func_name:"..func_name);
        if func_name == "user_info" then
            friend_tips_control.user_info();
        elseif func_name == "web_mouseenter" then
            friend_tips_view.on_mouse_hover_on_web_ctrl();
        elseif func_name == "web_mouseleave" then
            friend_tips_view.on_mouse_leave_on_web_ctrl();
        elseif func_name == "web_gotdata" then
            friend_tips_view.reset_size(true);
        elseif func_name == "web_cache" then
            friend_tips_control.web_cache(json_str);
        elseif func_name == "get_friend_game_state" then
            friend_tips_control.get_friend_game_state(json_str);
        end
    end;

    user_info = function()
        base_utility.log("[friend_tips_control] user_info");
        local call_param = {};
        call_param["retCode"] = 0;
        call_param["msg"] = "success";
        call_param["data"] = {};
        call_param["data"]["tgpid"] = friend_tips_view.friend_id;
        local friend_data_cache = friend_tips_control.get_valid_data(friend_tips_view.friend_id);
        if friend_data_cache ~= nil then
            call_param["data"]["cache"] = friend_data_cache;            
            friend_tips_view.reset_size(true);
        end

        call_param["data"]["type"] = 0; -- 0 -- 非文字直播  1 -- LOL 文字直播
        local status, game_id = friend_list_model.get_friend_status(friend_tips_view.friend_id);
        base_utility.log("[friend_tips_control] user_info, status:"..tostring(status)..", game_id:"..tostring(game_id));
        if game_id == GAME_ID.GAME_ID_LOL and friend_tips_control.is_lol_in_battle(friend_tips_view.friend_id) == true then
            local game_status, game_sub_status = friend_list_model.get_friend_game_detail_status(friend_tips_view.friend_id, game_id); 
            base_utility.log("[friend_tips_control] user_info, game_status:"..tostring(game_status)..", game_sub_status:"..tostring(game_sub_status));

            -- 游戏结束状态时设置为0， 不显示游戏文字直播（web拉取数据不到了）
            if tonumber(game_status) == 5 or tonumber(game_sub_status) == 5 then
                call_param["data"]["type"] = 0;
            else
                call_param["data"]["type"] = 1;
            end
        end

        call_param["data"]["game_id_list"] = friend_tips_control.query_friend_recent_game_list(friend_tips_view.friend_id);


        web_utility.lua_call_js_by_id("user_info",base_utility.table_to_json(call_param), friend_tips_view.dwLolGameInfoAreaId);
    end;

    is_lol_in_battle = function(friend_id)
        local out = comm_center.call_service('i_service_lol_game_status_is_in_live_status', {friend_id = friend_id});
        return out.is_live;
    end;

    web_cache = function(json_str)
        base_utility.log("[friend_tips_control] web_cache");
        local cache_info_tbl = base_utility.json_to_table(json_str);
        local tgp_id = cache_info_tbl["tgpid"];
        friend_tips_control.data_cache[tgp_id] = {time = os.time(), cache = cache_info_tbl["cache"]};
    end;

    get_friendlist_done = function(event_id, json_str)
        local friend_table = base_utility.json_to_table(json_str)
        if friend_table.friends and #friend_table.friends > 0 then

            table.insert(friend_table.friends, {friend_id = login_model.im_login_infomation.friend_id});

            local max_req_cnt = 50;
            local total_cnt = #friend_table.friends;
            local loop_cnt = math.ceil(total_cnt / max_req_cnt);

            for i = 1, loop_cnt do
                local friend_list = {};
                for j = (i - 1)*max_req_cnt + 1, i*max_req_cnt do
                    if j <= total_cnt then
                        table.insert(friend_list, friend_table.friends[j].friend_id);
                    else
                        break;
                    end
                end
                friend_tips_control.get_recent_play_game_list(friend_list);
            end
        end
    end;

    service_call_tgp_get_recent_game_list = function(data_in)
        --friend_tips_control.get_recent_play_game_list(data_in.list);
        data_out = {};
        data_out.result = 0;
        local friend_content_list = {};
        if data_in.list ~= nil and type(data_in.list) == "table" then
            for id_index = 1, #data_in.list do
                local friend_id = data_in.list[id_index];

                local list = friend_tips_control.friend_recent_game_list[friend_id];
                local ret = false;

                local game_id_list = {};
                if list ~= nil then
                    for i = 1, #list do
                        table.insert(game_id_list, list[i].game_id);
                    end
                end
                friend_content_list[tostring(friend_id)] = game_id_list;
            end
        end
        data_out.content = base_utility.table_to_json(friend_content_list);
        comm_center.send_broadcast('i_broadcast_to_cross_get_recent_game_list', data_out);
    end;

    get_recent_play_game_list = function(id_list)
    --[[
       if #id_list > 0 then
            local url = LoadStr("GET_RECENT_GAMELIST_URL");
            local is_first = true;
            for i = 1, #id_list do
                if is_first then
                    url = url..tostring(id_list[i]);
                    is_first = false;
                else
                    url = url.."|"..tostring(id_list[i]);
                end
            end
            base_utility.log("[friend_tips_control] get_recent_play_game_list:"..tostring(url));
            --url = web_utility.make_login_status_url(url, login_model.current_uin);
            base_utility.curl_request_async(url, "friend_tips_control.on_get_recent_play_game_list", true, nil,true);
        end
    --]]
    end;

    on_get_recent_play_game_list = function(result)
        if result == nil then
            base_utility.log("[friend_tips_control] on_get_recent_play_game_list: result is null");
            return;
        end

        local data_out = {};
        local param = base_utility.json_to_table(result);
        if param ~= nil and param.ErrorCode ~= nil then
            data_out.result = param.ErrorCode;
        else
            data_out.result = 4444;
        end
        
        if param ~= nil and type(param) == "table" then
            if param.ErrorCode == 0 and param.Data ~= nil then
                local friend_content_list = {};
                for friend_id, list in pairs(param.Data) do
                    friend_tips_control.friend_recent_game_list[tostring(friend_id)] = {};
                    local game_id_list = {};
                    for game_id_key, game_info_value in pairs(list) do
                        local result = comm_center.call_service('i_service_is_game_supported', {game_id = tonumber(game_id_key)});
                        if result.is_supported then -- 只保留版本支持的游戏
                            table.insert(friend_tips_control.friend_recent_game_list[tostring(friend_id)], {game_id = game_id_key, logintime = game_info_value[1]});
                            table.insert(game_id_list, game_id_key);
                        end
                    end
                    friend_content_list[tostring(friend_id)] = game_id_list;
                    comm_center.send_broadcast("i_broadcast_social_update_game_status", {friend_id = friend_id});
                end
                data_out.content = base_utility.table_to_json(friend_content_list);
                comm_center.send_broadcast('i_broadcast_to_cross_get_recent_game_list', data_out);
                comm_center.call_service('i_service_social_re_sort_friend_list', {});
                if friend_vlist_control ~= nil then
                    friend_vlist_control.update_ui();
                end
                if friend_tips_view ~= nil and friend_tips_view.is_show() then
                    friend_tips_view.update_friend_info();
                    friend_tips_control.user_info();
                end
            end
        end
    end;

    service_get_played_game_list = function(data_in)
        local friend_id = data_in.friend_id;
        return {list = friend_tips_control.query_friend_recent_game_list(friend_id)};
    end;

    service_is_game_id_in_friend_played_game_list = function(data_in)
        local friend_id = tostring(data_in.friend_id);
        local game_id = tonumber(data_in.game_id);
        local list = friend_tips_control.friend_recent_game_list[friend_id];
        local ret = false;

        if list ~= nil then
            for i = 1, #list do
                if tonumber(list[i].game_id) == game_id then
                    ret = true;
                    break;
                end
            end
        end

        -- check if game suported by current client version
        if ret == true then
            local result = comm_center.call_service('i_service_is_game_supported', {game_id = game_id});
            if result.is_supported then
                -- suported
            else
                ret = false; -- not supported
            end
        end

        return {is_played = ret};
    end;

    query_friend_recent_game_list = function(friend_id)
        return friend_tips_control.friend_recent_game_list[tostring(friend_id)];
    end;

    --新增好友时查询最近游戏大区
    on_add_friend_into_friend_list = function(event_id, json_str)
        base_utility.log("[friend_tips_control] on_add_friend_into_friend_list:"..json_str, true);
        local param = base_utility.json_to_table(json_str);

        local id_list = {};
        table.insert(id_list, param["friend_id"]);
        friend_tips_control.get_recent_play_game_list(id_list);
    end;

    on_lol_game_staus_changed = function(data)
        if friend_tips_view ~= nil and friend_tips_view.pDialog ~= nil then
             friend_tips_view.update_lol_game_status(data);
        end
    end;

     -- lol事件数据发送改变
    on_lol_event_data_changed = function(param_tbl)
        if nil == param_tbl then return end
        if friend_tips_view ~= nil and friend_tips_view.is_show() and 
            tostring(param_tbl["tgp_id"]) == friend_tips_view.friend_id then
            local param_table = {};
            param_table["retCode"] = 0;
            param_table["friend_id"] = param_tbl["tgp_id"];
            param_table["data"] = param_tbl["detail_info"];
            web_utility.lua_call_js_by_id("update_friend_lol_event_data"
                , base_utility.table_to_json(param_table), friend_tips_view.dwLolGameInfoAreaId);
        end
    end;

    update_lol_game_status_response = function(tbl_id_list)
        if friend_tips_view ~= nil and friend_tips_view.is_show() then
            if tbl_id_list["update_status_list"] ~= nil and #tbl_id_list["update_status_list"] > 0 then
                for i, user_id in ipairs(tbl_id_list["update_status_list"]) do
                    if user_id == friend_tips_view.friend_id then
                        local param_table = friend_tips_control.get_valid_lol_status_data_helper(user_id);
                        web_utility.lua_call_js_by_id("update_friend_lol_event_data"
                                , base_utility.table_to_json(param_table), friend_tips_view.dwLolGameInfoAreaId);
                        break;   -- 如果找到了，则退出循环
                    end
                end
            end
        end
    end;

    get_friend_game_state = function(json_str)
        local param_tbl = base_utility.json_to_table(json_str);
        if param_tbl ~= nil then
            local param_table = friend_tips_control.get_valid_lol_status_data_helper(param_tbl["friend_id"]);
            web_utility.lua_call_js_by_id("get_friend_game_state", base_utility.table_to_json(param_table)
                ,friend_tips_view.dwLolGameInfoAreaId);  
            -- 启动一次一次性的查询：
            local msg_param = { 
                tgp_id = param_tbl["friend_id"]
            };
            local ret_playing_lol = comm_center.call_service("i_service_lol_game_status_is_playing_lol_game", msg_param);
            if 1 == ret_playing_lol.is_playing_lol then
                local user_id_params = {
                    user_list = {param_tbl["friend_id"]}
                };
                comm_center.call_service("i_service_social_info_center_set_lol_once_query_list", user_id_params);
            end
        end
    end;

    get_valid_lol_status_data_helper = function(tgp_id_param)
        if nil == tgp_id_param then return end
        -- 获取lol的事件数据
        local msg_param = { 
            tgp_id = tgp_id_param
        };
        local ret_lol_status_tbl = comm_center.call_service(
                "i_service_social_info_center_get_lol_player_status", msg_param);
        local param_table = {};
        param_table["retCode"] = 0;
        param_table["friend_id"] = ret_lol_status_tbl["tgp_id"];
        -- 检查是否正在玩lol
        local ret_playing_lol = comm_center.call_service("i_service_lol_game_status_is_playing_lol_game", msg_param);
        if 1 == ret_playing_lol.is_playing_lol then 
            -- 校验数据是否有效
            local ret_valid_tbl = comm_center.call_service("i_service_lol_game_status_check_lol_status_valid", msg_param);
            if 1 == ret_valid_tbl.is_valid then
                param_table["data"] = ret_lol_status_tbl["detail_info"];
            else
                param_table["data"] = friend_tips_control.modify_lol_user_status_data(ret_lol_status_tbl);
                base_utility.log("[friend_tips_control] ret invalid data, overdue");
            end
        else
            -- 没有玩lol，直接返回-1
            param_table["data"] = friend_tips_control.modify_lol_user_status_data(ret_lol_status_tbl);
            base_utility.log("[friend_tips_control] not playing lol game.");
        end
        return param_table;
    end;

    handle_lol_user_status_exception = function(event_id, json_str)
        local param_tbl = base_utility.json_to_table(json_str);
        if param_tbl ~= nil and param_tbl.tgp_id ~= nil then
             if friend_tips_view ~= nil and friend_tips_view.is_show() and 
                tostring(param_tbl["tgp_id"]) == friend_tips_view.friend_id then
                local param_table = {};
                param_table["retCode"] = 0;
                param_table["friend_id"] = param_tbl["tgp_id"];
                
                local ret_tbl = comm_center.call_service("i_service_social_info_center_get_lol_player_status", param_tbl);
                param_table["data"] = friend_tips_control.modify_lol_user_status_data(ret_tbl);
               
                web_utility.lua_call_js_by_id("update_friend_lol_event_data", base_utility.table_to_json(param_table)
                    ,friend_tips_view.dwLolGameInfoAreaId);
            end
        end
    end;

    modify_lol_user_status_data = function(ret_status_tbl)
         local ret_json = "";
         if ret_status_tbl ~= nil and ret_status_tbl.detail_info ~= nil 
            and ret_status_tbl.detail_info ~= "" and ret_status_tbl.detail_info ~= "0" then
            local param = base_utility.json_to_table(ret_status_tbl.detail_info);
            if param ~= nil and "table" == type(param) and param.d ~= nil and "table" == type(param.d) then
                param.d[4] = -1;     -- 修改event_type为异常的-1
            end 
            ret_json = base_utility.table_to_json(param);
         end
         return ret_json;
    end;

    recv_friend_report = function(event_id, json_str)
        local param = base_utility.json_to_table(json_str);
        if param.nType == 0xFF then
            local status_param = base_utility.json_to_table(param["szRemark"]);
            if status_param.type == "status_change" then
                if status_param.tgp_id ~= nil then
                    if friend_tips_view ~= nil and friend_tips_view.is_show() and 
                        tostring(status_param["tgp_id"]) == friend_tips_view.friend_id then
                           
                        local param_table = {};
                        param_table["retCode"] = 0;
                        param_table["data"] = {};
                        param_table["data"]["friend_report"] = param;

                        web_utility.lua_call_js_by_id("recv_friend_report", base_utility.table_to_json(param_table), 
                            friend_tips_view.dwLolGameInfoAreaId);  
                    end
                end
            end
        end
    end;

    is_setting_only_self_visible = function ()
        local is_only_self_visible = false;
        local data = comm_center.call_service("i_service_get_my_setting", {key = "my_game_limit"});
        if nil ~= data and nil ~= data.value then
             if 2 == data.value then
                 is_only_self_visible = true;
             end
        end

        return is_only_self_visible;
    end;

    handle_show_wegame_online_tips = function (data)
        if base_utility.is_type_of_oversea_ver() then
            return;
        end
        if nil == data or nil == data.friend_id then
            base_utility.log(string.format("[handle_show_wegame_online_tips]data is nil"));
            return;
        end
        local tip_data = {};
        tip_data.id = os.time();
        tip_data.tips_main_type = tip_type_constant.MAIN_TYPE_NORMAL;
        tip_data.tips_sub_type = tip_type_constant.sub_type_wegame_online;

        local user_info = comm_center.call_service("i_service_social_get_user_detail_info", {friend_id = data.friend_id});
        if nil == user_info then
             return;
        end
        tip_data.tips_icon = user_info.url;
        tip_data.icon_type = tip_type_constant.ICON_TYPE_CIRCULAR;

        -- tips标题
        local title = LoadStr("SOCIAL_FRIEND_ONLINE_TIPS_TITILE");
        tip_data.tips_title = title;

        -- tips主体内容
        local nick_name = user_info.new_name or "";
        if "" == nick_name then
            nick_name = user_info.name;
        end
        local content = "";
        local name_cui, name_hoder;
        if (string.find(nick_name, "[^a-z0-9_]") == nil) then --全小写英文和标点
            name_cui, name_hoder = U8toCUIStrn(nick_name, 11, 1);
        else
            name_cui, name_hoder = U8toCUIStrn(nick_name, 7, 1);
        end
        local name_u8 = CUIStrtoU8(name_cui);
        if base_utility.is_type_of_oversea_ver() then
           content = '<f c="0xffb219">' .. name_u8 .. '</f>' .. LoadStr("SOCIAL_WEGAME_ONLINE_TIPS_CONTENT");
        else
           content = '<f c="0x00abfa">' .. name_u8 .. '</f>' .. LoadStr("SOCIAL_WEGAME_ONLINE_TIPS_CONTENT");
        end
        -- content = name_u8 .. LoadStr("SOCIAL_WEGAME_ONLINE_TIPS_CONTENT");
        tip_data.main_title = content;
        -- 设置点击回调
        tip_data.tips_setting = 1;
        tip_data.setting_service = "i_broadcast_open_msg_setting";
        tip_data.show_duration = 5000;

        comm_center.send_broadcast("i_broadcast_tips_show_com", tip_data);
        tips_reveive_common.tips_qos("wg_common_tip", "client_show", tip_data);
    end;

    handle_show_game_online_tips = function (data)
        if base_utility.is_type_of_oversea_ver() then
            return;
        end
        local tip_data = {};
        tip_data.id = os.time();
        tip_data.tips_main_type = tip_type_constant.MAIN_TYPE_NORMAL;
        tip_data.tips_sub_type = tip_type_constant.sub_type_game_online;
        tip_data.game_id = data.game_id;

        local user_info = comm_center.call_service("i_service_social_get_user_detail_info", {friend_id = data.friend_id});
        if nil == user_info then
             return;
        end
        tip_data.tips_icon = user_info.url;
        tip_data.icon_type = tip_type_constant.ICON_TYPE_CIRCULAR;

        -- tips标题
        local title = LoadStr("SOCIAL_FRIEND_ONLINE_TIPS_TITILE");
        tip_data.tips_title = title;

        -- tips主体内容
        local nick_name = user_info.new_name or "";
        if "" == nick_name then
            nick_name = user_info.name;
        end
        local content = "";
        local name_cui, name_hoder;
        if (string.find(nick_name, "[^a-z0-9_]") == nil) then --全小写英文和标点
            name_cui, name_hoder = U8toCUIStrn(nick_name, 11, 1);
        else
            name_cui, name_hoder = U8toCUIStrn(nick_name, 7, 1);
        end
        local name_u8 = CUIStrtoU8(name_cui);
        if base_utility.is_type_of_oversea_ver() then
           content = '<f c="0xffb219">' .. name_u8 .. '</f>' .. LoadStr("SOCIAL_GAME_ONLINE_TIPS_CONTENT"); 
        else 
           content = '<f c="0x00abfa">' .. name_u8 .. '</f>' .. LoadStr("SOCIAL_GAME_ONLINE_TIPS_CONTENT");
        end
        tip_data.main_title = content;
        -- 设置点击回调
        tip_data.tips_setting = 1;
        tip_data.setting_service = "i_broadcast_open_msg_setting";
        tip_data.show_duration = 5000;

        if nil ~= data.game_name and "" ~= data.game_name then
            tip_data.sub_title = data.game_name;
        else
            local game_info = banner_model.get_game_base_info(data.game_id);
            if nil ~= game_info then
                tip_data.sub_title = game_info.name;
            end
        end

        tip_data.tips_ok_btn = LoadStr("SOCIAL_GAME_ONLINE_TIPS_START_GAME");
        tip_data.ok_service = "i_service_game_online_tips_start_game";

        comm_center.send_broadcast("i_broadcast_tips_show_com", tip_data);
        tips_reveive_common.tips_qos("wg_common_tip", "client_show", tip_data);
    end;

    open_msg_setting = function (data)
        local url = LoadStr("OPEN_MSG_SET_URL");
        if 0 ~= wegame_mainframe_model.self_tgp_id then
            url = url.."&tgpid="..tostring(wegame_mainframe_model.self_tgp_id);
        end;
        local param = {};
        param.type = "jump_url";
        param.id = GAME_ID.GAEM_ID_HOME_PAGE;
        param.url = url;
        param.op_from = 0;
        local json_str = base_utility.table_to_json(param);
        web_utility.open_link(json_str);
    end;

    handle_game_online_tips_dl_game = function (data)
        if nil == data or nil == data.game_id then
            return;
        end
        -- 先打开助手页
        -- friend_tips_control.open_helper_page(data.game_id);
        comm_center.call_service("i_service_downlaod_game", {game_id = data.game_id});
    end;

    handle_game_onlie_tips_start_game = function (data)
        if nil == data or nil == data.game_id then
            return;
        end
     
        -- 打开助手页即可
        friend_tips_control.open_helper_page(data.game_id);
    end;

    open_helper_page = function (game_id)
        local table_str = {};
        table_str.type = "landing";
        table_str.game_id = game_id;
        local json_str = base_utility.table_to_json(table_str);
        web_utility.open_link(json_str);
    end;
};

friend_tips_control.init();